package com.oak.broke.interceptor;

import com.oak.broke.constant.ResponseConstant;
import com.oak.broke.exception.VipException;
import com.oak.broke.properties.CustomProperties;
import com.oak.broke.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author tanghan
 * @Description ip白名单拦截器
 * @date 2023/04/19/ 17:19:00
 */
@Component
@Slf4j
public class IpInterceptor implements HandlerInterceptor {

    @Autowired
    private CustomProperties customProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        List<String> whiteIpList = customProperties.getWhiteIpList();
        String ip = IpUtil.getIpAddr(request);
        if (CollectionUtils.isEmpty(whiteIpList)) {
            log.warn("未配置请求IP白名单，无法请求");
            throw new VipException(ResponseConstant.WHITE_LIST_NOT_EXIST);
        }
        if (whiteIpList.contains(ip)) {
            return true;
        } else {
            log.error("请求IP：【{}】不在白名单中", ip);
            throw new VipException(ResponseConstant.REQUEST_IP_NOT_IN_WHITE_LIST, ip);
        }

    }
}
